<template>
  <div
    class="comp-radio-group"
    :class="{
      'comp-radio-group--horizontal': direction === 'horizontal',
      'comp-radio-group--button': button
    }"
  >
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
  import { provide, ref, computed, type Ref } from 'vue';
  import type { RadioGroupContext } from './Index.vue';

  export interface RadioGroupProps {
    modelValue?: string | number | boolean;
    disabled?: boolean;
    direction?: 'vertical' | 'horizontal';
    button?: boolean;
    name?: string;
  }

  export interface RadioGroupEmits {
    (e: 'update:modelValue', value: string | number | boolean): void;
    (e: 'change', value: string | number | boolean): void;
  }

  const props = withDefaults(defineProps<RadioGroupProps>(), {
    modelValue: undefined,
    disabled: false,
    direction: 'vertical',
    button: false,
    name: ''
  });

  const emit = defineEmits<RadioGroupEmits>();

  // 更新选中值
  const updateValue = (value: string | number | boolean) => {
    emit('update:modelValue', value);
    emit('change', value);
  };

  // 创建响应式的上下文对象
  const radioGroupContext = computed<RadioGroupContext>(() => ({
    modelValue: props.modelValue,
    disabled: props.disabled,
    updateValue,
    name: props.name
  }));

  // 提供上下文给子组件
  provide<Ref<RadioGroupContext>>('radioGroup', radioGroupContext);

</script>

<style lang="scss" scoped>
  .comp-radio-group {
    display: inline-flex;
    flex-direction: column;
    align-items: flex-start;

    &--horizontal {
      flex-direction: row;
      flex-wrap: wrap;
    }

    &--button {
      display: inline-flex;
      border-radius: 4px;
      overflow: hidden;

      :deep(.comp-radio) {
        margin-right: 0;
        border-radius: 0;
        border-right-width: 0;

        &:first-child {
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }

        &:last-child {
          border-right-width: 1px;
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }
      }
    }
  }
</style>